package shanghaielectric_lib.Communication.Comm_Modbus;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.shanghai.shanghaielectric.Constants;
import com.shanghai.shanghaielectric.Model.EventBus.EventbusModel_Tag;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import shanghaielectric_lib.Communication.CommunicateManager;
import shanghaielectric_lib.DB.DBHelper_config;
import shanghaielectric_lib.DeviceConfigModel.Device.Device;
import shanghaielectric_lib.MyEventBus.EventBus_int_bool;
import shanghaielectric_lib.RDBHelper.RDBHelper;
import shanghaielectric_lib.Utils.LogUtil;

/**
 * Created by 45000460 on 2017/11/21.
 */

public class ModbusThread extends Thread {
    String TAG = "ModbusThread";
    private Comm_Modbus comm_modbus;
    private RDBHelper rdbHelper;
    private List<Device> deviceList;
    public static boolean isModbusThreadRunning = false;//线程是否运行标志位
    public static boolean isWriteData = false;
    static int count_writeDataTimes = 5;//下发一次写数据命令，执行命令次数
    static int currentPackageID = 1;//下发一次写数据命令，执行命令次数
    public static final int CONNECT_TIME = 5;//判断通信是否正常循环次数
    public static int communicateTestTimes_temp = 2;//判断通信是否正常循环次数
    private boolean[] deviceCommunicateState_temp = new boolean[DBHelper_config.getDBHelper_config().getDevices().size()];
    public static int communicateTestTimes_normal = 5;//判断通信是否正常循环次数_正常通信
    private boolean[] deviceCommunicateState_temp_normal = new boolean[DBHelper_config.getDBHelper_config().getDevices().size()];
    public static boolean isrefreshCommunicate = true;//是否正在刷新通信
    public static boolean isFirstCommunicateFlag = true;//是否是首次或重新刷新了通信的标志位

    @RequiresApi(api = Build.VERSION_CODES.N)
    public ModbusThread() {
        comm_modbus = new Comm_Modbus();
        rdbHelper = RDBHelper.getInstance();
        deviceList = DBHelper_config.getDBHelper_config().getDeviceList();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void run() {
        super.run();
        isModbusThreadRunning = true;
        while (isModbusThreadRunning) {
            while (!Constants.isSettingParameter) {
                for (int i = 0; i < deviceList.size(); i++) {
                    //找到链接中的单元，进行通信
                    if (isFirstCommunicateFlag | Constants.deviceStates[deviceList.get(i).deviceID_d - 1].isConnect) {
                       if (isFirstCommunicateFlag){//第一次连接，发全部数据
                           Constants_modbus.isSettingState=true;
                       }
                        EventBus_int_bool eventBus_int_bool = new EventBus_int_bool();
                        eventBus_int_bool.id = deviceList.get(i).deviceID_d;
                        eventBus_int_bool.flag = true;
                        if (isrefreshCommunicate) {
                            EventBus.getDefault().post(eventBus_int_bool);
                        }
                        if (!Constants.isSettingParameter)
                            try {
                                Thread.sleep(Constants.SLEEP_TIME_50);//1225
                                LogUtil.e("modbusThread", "sleep-x  50ms");
                                comm_modbus.sendRequest(deviceList.get(i).deviceID_d);

//                                if (isWriteData) {
//                                    if (Constants_modbus.isSettingState) {
//                                        if (count_writeDataTimes > 0) {
//                                            for (int j = 1; j < 6; j++) {//必须确保这段代码执行完毕
//                                                Thread.sleep(Constants.SLEEP_TIME_200);
//                                                LogUtil.e("modbusThread", "sleep-1  21ms");
//                                                comm_modbus.writeData(1, j);
//                                            }
//                                            count_writeDataTimes--;
//                                        } else {
//                                            isWriteData = false;
//                                            CommunicateManager.clearData_0_3();
//                                        }
//                                    } else {
//                                        isWriteData = false;
//                                        count_writeDataTimes = 0;
//                                        CommunicateManager.clearData_0_3();
//                                    }
//                                } else {
//                                    // TODO: 2017/12/1  除了在设置和scan,其他时间一直要发
//                                    if (!Constants_modbus.isSettingState && !Constants.isScanState) {
//                                        Thread.sleep(Constants.SLEEP_TIME_50);
//                                        LogUtil.e("modbusThread", "sleep-2  100ms");
//                                        comm_modbus.writeData(1, 1);
//                                    }
//                                }
                                //write----
                                Thread.sleep(Constants.SLEEP_TIME_200);
                                LogUtil.e("modbusThread", "sleep-4  200ms");
                                //连续判断5次，5次都没连接上的视为设备不存在
                                boolean flag = comm_modbus.readData(deviceList.get(i).deviceID_d);
//                            Thread.sleep(Constants.REQUEST_SLEEP_TIME);// have1225
//                            LogUtil.e("modbusThread", "sleep-5  210ms"); // have1225
                                eventBus_int_bool.flag = flag;
                                if (isrefreshCommunicate) {//正在刷新通信
                                    EventBus.getDefault().post(eventBus_int_bool);
                                    if (flag) {
                                        deviceCommunicateState_temp[deviceList.get(i).deviceID_d - 1] = true;
                                    }
                                } else {
                                    if (!flag) {//正常通信情况下，有设备掉线，发布设备连接情况
//                            EventBus.getDefault().post(Constants.CommunicateStateChanged);
                                    }
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                    }
                }
                //请求数据，读一轮 后 写数据==============================================================
                try {
                    if (isWriteData) {
                        Log.e("chb","isWriteData"+isWriteData);
                        if (Constants_modbus.isSettingState) {
                            Log.e("chb","isSettingState"+Constants_modbus.isSettingState);
                            if (count_writeDataTimes > 0) {
                                for (int j = 1; j < 6; j++) {//必须确保这段代码执行完毕
                                    Thread.sleep(Constants.SLEEP_TIME_50);
                                    LogUtil.e("modbusThread", "sleep-1  50ms");
                                    comm_modbus.writeData(1, j);
                                }
                                count_writeDataTimes--;
                            } else {
                                isWriteData = false;
                                CommunicateManager.clearData_0_3();
                                Constants_modbus.isSettingState=false;

                            }
                        } else {
                            Log.e("chb","isSettingState"+Constants_modbus.isSettingState);
//                            isWriteData = false;
//                            count_writeDataTimes = 0;
                            if (count_writeDataTimes > 0) {
                                    LogUtil.e("modbusThread", "sleep-1  50ms");
                                    comm_modbus.writeData(1, 1);
                                count_writeDataTimes--;
                            } else {
                                isWriteData = false;
                                CommunicateManager.clearData_0_3();
                            }
                        }
                    } else {
                        // TODO: 2017/12/1  除了在设置和scan,其他时间一直要发
                        if (!Constants_modbus.isSettingState && !Constants.isScanState) {
                            Thread.sleep(Constants.SLEEP_TIME_50);
                            LogUtil.e("modbusThread", "sleep-2  50ms");
                            comm_modbus.writeData(1, 1);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }


//                ========================================================================================
                if (isrefreshCommunicate) {//正在刷新通信的情况下
                    communicateTestTimes_temp--;
                    //5次后获得设备最终连接情况
                    if (communicateTestTimes_temp < 0) {
//                    Constants.DEVICE_COMMUNICATE_STATE = deviceCommunicateState_temp;
                        for (int i = 0; i < Constants.deviceStates.length; i++) {
                            Constants.deviceStates[i].isConnect = deviceCommunicateState_temp[i];
                        }
//                    LogUtil.e(TAG, "设备" + ArrayUtils.toString(Constants.DEVICE_COMMUNICATE_STATE));
                        isrefreshCommunicate = false;
                        isFirstCommunicateFlag = false;
                        //扫描结束：
                        EventbusModel_Tag eventbusModel_tag = new EventbusModel_Tag();
                        eventbusModel_tag.tag = EventbusModel_Tag.UPDATE_COMMUNICATE;
                        EventBus.getDefault().post(eventbusModel_tag);

                    }
                }
            }
        }
        comm_modbus.closePort();
    }

    public static void startWriteData() {
        count_writeDataTimes = CONNECT_TIME;
        currentPackageID = 1;
        isWriteData = true;
    }

    public static void refreshCommunicate() {
        isFirstCommunicateFlag = true;
        isrefreshCommunicate = true;
        communicateTestTimes_temp = CONNECT_TIME;
    }
}
